<template>
    <div>
        <div class="searchArea">
            <el-input v-model="account" placeholder="账号" class="searchTextInput" clearable/>
            <el-input v-model="nickName" placeholder="昵称" class="searchTextInput" clearable/>
            <el-button type="primary" class="searchButton" @click="searchAccountAction">查询</el-button>

            <div class="addAccountArea">
                <el-button type="primary" class="searchButton" @click="addAccountAction" plain>新增</el-button>
            </div>
        </div>

        <div class="table">
            <el-table 
            :data="tableData" 
            style="width: 100%" 
            max-height="500"
            stripe 
            border 
            :cell-style="{textAlign:'center'}"
            :header-cell-style="{textAlign:'center'}"
            >
                <el-table-column prop="id" label="ID" width="50" />
                <el-table-column prop="username" label="用户名" min-width="88" :formatter="formatUserName"/>
                <el-table-column prop="nickName" label="昵称" min-width="88" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClickEdit(scope.row)"
                        :disabled="scope.row.username == userInfo.username || scope.row.username == tenantInfo.admin">编辑</el-button>
                        <el-button link type="primary" size="small" @click="handleClickDel(scope.row)" style="margin-left:0px;"
                        :disabled="scope.row.username == userInfo.username || scope.row.username == tenantInfo.admin">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100, 150, 200, 250, 300]"
                :small="false"
                :disabled="false"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                total-text="总共"
                style="justify-content:end"
            />
        </div>
        <AddAccountDialog v-model:isShow="isShowAddAccountDialog" :handleUpdated="handleUpdated"></AddAccountDialog>
        <EditAccountDialog v-model:isShow="isShowEditAccountDialog" :handleUpdated="handleUpdated" v-model:data="selectedData"></EditAccountDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed, defineProps, defineEmits, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import TenantApi from '../../apis/tenant'
import AddAccountDialog from '../MyTenant/AddAccountDialog.vue'
import EditAccountDialog from './EditAccountDialog.vue';
import { storeToRefs } from 'pinia'
import {useUserStore} from '../../stores/user'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore);

const router = useRouter();
const route = useRoute();

var tableData:any = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(200)

const account = ref("");
const nickName = ref("");
const isShowAddAccountDialog = ref(false);
const isShowEditAccountDialog = ref(false);
const selectedData = ref();
const tenantInfo = ref();
onMounted(()=>{
    loadData();
})

const searchAccountAction = () =>{
    loadData();
}

const loadData = () => {
    TenantApi.fetchTenantInfo().then(ret=>{
        if(ret.code == 0){
            tenantInfo.value = ret.data;
        }else{
            ElMessage({
                type: 'error',
                message: ret.message,
            })
        }
        return TenantApi.fetchTenantAccounts(account.value, nickName.value, currentPage.value-1, pageSize.value);
    }).then(ret=>{
        if(ret.code == 0){
            tableData.value = ret.data.list;
            total.value = ret.data.totalCount;
            currentPage.value = ret.data.page+1;
            pageSize.value = ret.data.pageSize;
        }else{
            ElMessage({
                type: 'error',
                message: ret.message,
            })
        }
        return TenantApi.fetchTenantInfo();
    }).then(ret=>{
        if(ret.code == 0){
            tenantInfo.value = ret.data;
        }else{
            ElMessage({
                type: 'error',
                message: ret.message,
            })
        }
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err,
        })
    })
}


const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  loadData();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  loadData();
}

const handleClickEdit = (row:any)=>{
    console.log('[AccountsMgr]handleClickEdit', row);
    selectedData.value = row;
    isShowEditAccountDialog.value = true;
}

const handleClickDel = (row:any)=>{
    console.log('[AccountsMgr]handleClickDel', row);
    ElMessageBox.confirm(`确认删除${row.username}吗?`,'温馨提示',{
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(ret=>{
        return TenantApi.delTenantAccount(row.username)
    }).then(ret=>{
        if(ret.code == 0){
            loadData();
            ElMessage({
                type: 'success',
                message: "删除成功",
            });
        }else{
            ElMessage({
                type: 'error',
                message: "删除失败",
            });
        }
    }).catch(err=>{
        if(err=="cancel"){
            ElMessage({
                type: 'info',
                message: "取消删除操作",
            })
        }else{
            ElMessage({
                type: 'error',
                message: "删除失败",
            })
        }
    });
}

const addAccountAction = ()=>{
    isShowAddAccountDialog.value = true;
}

const handleUpdated = ()=>{
    loadData();
}

const formatUserName = (row:any, column:any, cellValue:any, index:any)=>{
    const username = cellValue;
    let newUserName = username
    if(userStore.userInfo.username == username){
        newUserName = newUserName + "[当前用户]"
    }
    if(tenantInfo.value.admin == username){
        newUserName = newUserName + "[管理员]"
    }
    return newUserName;
}
</script>

<style scoped>
.searchArea {
    display: flex;
    padding-bottom: 10px;
}
.searchButton {
    margin-left: 0px;
}
.searchTextInput {
    width: 120px;
    margin-right: 10px;
}
.pagination {
    margin-top: 15px;
}
.addAccountArea {
    display: inline-flex;
    position: absolute;
    right: 20px;
}
</style>
